package calao;

import calao.storage.EqualCondition;
import calao.storage.Record;
import calao.storage.Search;
import calao.util.Cursor;
import calao.util.Strings;

public class UserManager
extends Service
{

	public User getUser(String alias, String password)
	{
		Search search = new Search(User.TABLE);
		search.add(new EqualCondition(User.ALIAS, alias));
		Cursor<Record> cursor = ws.storage.listResults(search);
		try {
			if (cursor.next()) {
				Record rec = cursor.get();
				User user = new User(ws, rec);
				if (password==null 
						|| Strings.md5Hash(password).equals(user.passwordHash)) 
				{
					 return user;
				}
			}
		}
		finally {
			cursor.close();
		}
		return null;
	}
	
	public User getUser(long guid)
	{
		Record hit = ws.storage.fetch(User.TABLE, User.getUID(guid));
		return hit!=null? new User(ws, hit) : null;
	}
	
	public User createUser(String alias, String password)
	{
		return createUser(alias, password, null);
	}

	synchronized public User createUser(String alias, String password, String email)
	{
		// check for alias uniqueness
		User user = getUser(alias, null);
		if (user!=null) return null;
		user = new User(ws, ws.storage.getNextValue(User.ID_SEQUENCE), alias, email);
		user.setPassword(password);
		// create record
		store(user.id, alias, user.passwordHash, email);
		return user;
	}
	
	void store(int id, String alias, String passwordHash, String email)
	{
		Record record = new Record(User.TABLE);
		record.set(User.ID,	id);
		record.set(User.ALIAS, alias);
		record.set(User.PASSWORD_HASH, passwordHash);
		record.set(User.EMAIL, email);
		getWorkspace().storage.store(record);					
	}

	public Workspace getUserBaseWorkspace(long guid)
	{
		int uwsid = User.getUWSID(guid);
		Workspace uws = ws;
		while (uws!=null) {
			if (uws.id == uwsid) return uws;
			uws = uws.parent;
		}
		return null;
	}

}
